package com.muyun.data.modeler.infrastructure.general.specs;

import com.muyun.data.modeler.infrastructure.general.consts.MessageConsts;
import com.muyun.data.modeler.infrastructure.general.toolkit.SpringContextToolkit;
import org.springframework.context.support.MessageSourceAccessor;

/**
 * 所有响应结果的基类
 * 所有接口必须使用该类进行结果响应
 *
 * @author muyun12
 * @date 2020-12-19 19:06:26
 * @since
 */
public class ApiResponse<R> {

    private String reCode;
    private String reInfo;
    private R result;

    public String getReCode() {
        return reCode;
    }

    public void setReCode(String reCode) {
        this.reCode = reCode;
    }

    public String getReInfo() {
        return reInfo;
    }

    public void setReInfo(String reInfo) {
        this.reInfo = reInfo;
    }

    public R getResult() {
        return result;
    }

    public void setResult(R result) {
        this.result = result;
    }

    /**
     * 组装响应结果
     * @param result 响应结果数据
     * @param reCode 返回码
     * @param reInfo 返回信息
     * @param <R> 结果类型
     * @return
     */
    private static <R> ApiResponse<R> result(R result, String reCode, String reInfo) {
        ApiResponse<R> apiResponse = new ApiResponse<>();
        apiResponse.setReCode(reCode);
        apiResponse.setReInfo(reInfo);
        apiResponse.setResult(result);
        return apiResponse;
    }

    public static ApiResponse success() {
        return ApiResponse.success(null);
    }

    /**
     * 使用给定的响应结果创建业务处理成功的响应结果
     *
     * @param result
     * @param <R>
     * @return
     */
    public static <R> ApiResponse<R> success(R result) {
        return result(result, MessageConsts.CODE_0,
                SpringContextToolkit.getBean(MessageSourceAccessor.class).getMessage(MessageConsts.CODE_0));
    }

    public static ApiResponse fail(){
        return fail(null, MessageConsts.CODE_1,
                SpringContextToolkit.getBean(MessageSourceAccessor.class).getMessage(MessageConsts.CODE_1));
    }

    public static ApiResponse fail(String reInfo) {
        return fail(null, MessageConsts.CODE_1, reInfo);
    }

    public static ApiResponse fail(String reCode, String reInfo){
        return fail(null, reCode, reInfo);
    }

    /**
     * 使用给定的响应结果创建业务处理异常的响应结果
     *
     * @param result
     * @param <R>
     * @return
     */
    public static <R> ApiResponse<R> fail(R result) {
        return fail(result, MessageConsts.CODE_1,
                SpringContextToolkit.getBean(MessageSourceAccessor.class).getMessage(MessageConsts.CODE_1));
    }

    /**
     * 使用给定的响应结果创建业务处理异常的响应结果
     *
     * @param result
     * @param reCode
     * @param reInfo
     * @param <R>
     * @return
     */
    public static <R> ApiResponse<R> fail(R result, String reCode, String reInfo) {
        return result(result, reCode, reInfo);
    }


}
